<template>
  <div :class="['upload', 'mt-40', className]">
    <div class="upload-title text-30 font-normal leading-46 text-[#303133]" v-if="showLength">
      上传图片({{ imageList.length }}/{{ max }})
    </div>
    <div class="upload-content flex flex-wrap gap-32">
      <template v-for="item in imageList" :key="item">
        <div class="upload-item relative mt-16 flex items-center justify-center" :class="`size-${size}`">
          <image :src="item" class="size-full" />
          <image class="close absolute right-0 top-0 size-40" src="../../static/images/close.png" @tap="deleteImage(item)" />
        </div>
      </template>
      <div
        v-if="imageList.length < max"
        @tap="selectImage"
        class="upload-item relative mt-16 flex items-center justify-center"
        :class="`size-${size}`"
      >
        <image src="../../static/images/tousu/upload_empty.png" class="size-80" />
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref } from 'vue'
import { uploadImageApi } from '@/common/api/base'
const props = defineProps({
  className: {
    type: String,
    default: ''
  },
  max: {
    type: Number,
    default: 3
  },
  size: {
    type: Number,
    default: 200
  },
  fileList: {
    type: Array,
    default: () => []
  },
  showLength: {
    type: Boolean,
    default: true
  }
})

const emit = defineEmits(['fileListChange'])
const imageList = ref(props.fileList)

const selectImage = () => {
  uni.chooseImage({
    count: props.max - imageList.value.length,
    multiple: true,
    sizeType: ['original', 'compressed'],
    sourceType: ['album', 'camera'],
    success: (res: any) => {
      console.log('[ res ] >', res)

      res.tempFiles.forEach((file: any, index: number) => {
        uni.showLoading({
          title: `上传第 ${index + 1} 张...`
        })

        uploadImageApi({
          filePath: file.path
        })
          .then((data: any) => {
            console.log('[ data ] >', data)
            imageList.value.push(data.url)
            emit('fileListChange', imageList.value)
          })
          .finally(() => {
            uni.hideLoading()
            if (index === res.tempFiles.length - 1) {
              uni.showToast({
                title: '所有图片上传完成',
                icon: 'success'
              })
            }
          })
      })
    }
  })
}

const deleteImage = (file: any) => {
  imageList.value = imageList.value.filter((item: any) => item !== file)
  emit('fileListChange', imageList.value)
}
</script>

<style scoped lang="scss">
.upload-item {
  background: #fafafa;
  border-radius: 8rpx 8rpx 8rpx 8rpx;
  border: 1px solid #dcdfe6;
}
</style>
